﻿using MediatR;
using Microsoft.Extensions.Options;
using Sgr.Application;
using Sgr.Application.Commands;
using Sgr.Generator;
using Sgr.Identity;
using Sgr.Identity.Services;
using Sgr.Indentity.Application.ViewModels;

namespace Sgr.Indentity.Application.Commands
{
    /// <summary>
    /// 用户账号密码登录命令处理器
    /// </summary>
    public class UserLoginCommandHandle :
        LoginCommandHandleBase,
        IRequestHandler<UserLoginCommand, CommandResult<TokenViewModel>>
    {
        public UserLoginCommandHandle(
            IAccountAuthService accountService,
            IHttpContextAccessor httpContextAccessor,
            ISignatureChecker signatureChecker,
            IStringIdGenerator stringIdGenerator,
            IOptions<IdentityOptions> options,
            ILogger<UserLoginCommandHandle> logger)
            : base(accountService, httpContextAccessor, signatureChecker, stringIdGenerator, options, logger)
        {
        }

        /// <summary>
        /// 处理登录请求
        /// </summary>
        public async Task<CommandResult<TokenViewModel>> Handle(UserLoginCommand request, CancellationToken cancellationToken)
        {
            // 参数验证
            if (!ValidateRequest(request))
            {
                return CommandResult.Invalid<TokenViewModel>("请求参数无效");
            }

            // 验证账号
            var accountResult = await _accountService.ValidateAccountAsync(
                request.Name,
                request.Password,
                cancellationToken);

            // 处理登录结果
            return await ProcessLoginResultAsync(
                accountResult,
                request.Name,
                AccountLoginWay.Password,
                cancellationToken);
        }

        /// <summary>
        /// 验证请求参数
        /// </summary>
        private bool ValidateRequest(UserLoginCommand request)
        {
            // 基本参数验证
            if (string.IsNullOrWhiteSpace(request.Name) ||
                string.IsNullOrWhiteSpace(request.Password))
            {
                return false;
            }

            // 签名验证
            if (!ValidateSignature(
                request.Signature,
                request.Timestamp,
                request.Nonce,
                $"{request.Name}-{request.Password}",
                request.Password,
                request.Name))
            {
                return false;
            }

            // 验证码验证
            if (!ValidateImageVerificationCode(
                request.VerificationCode,
                request.VerificationHash,
                request.Name))
            {
                return false;
            }

            return true;
        }
    }
}